/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lvyh.lightframe.transaction.springcloud.proxy;


import com.alibaba.fastjson.JSON;
import com.lvyh.lightframe.transaction.common.constant.TransactionConstant;
import com.lvyh.lightframe.transaction.common.context.TransactionContext;
import com.lvyh.lightframe.transaction.common.domain.Participant;
import com.lvyh.lightframe.transaction.common.domain.RPCErrorInfo;
import com.lvyh.lightframe.transaction.common.thread.TransactionThreadLocal;
import com.lvyh.lightframe.transaction.core.context.ApplicationContextHolder;
import com.lvyh.lightframe.transaction.core.coordinator.TransactionCoordinatorSupport;
import com.lvyh.lightframe.transaction.core.context.SimpleRpcContext;
import com.lvyh.lightframe.transaction.springcloud.annotation.TransactionFeignClient;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Objects;

@Slf4j
public class TransactionFeignHandler implements InvocationHandler {

    private InvocationHandler delegate;

    @Override
    public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
        if (Object.class.equals(method.getDeclaringClass())) {
            return method.invoke(this, args);
        } else {
            final TransactionFeignClient myth = method.getAnnotation(TransactionFeignClient.class);
            if (Objects.isNull(myth)) {
                return this.delegate.invoke(proxy, method, args);
            }
            try {
                //Get the current transaction context object through ThreadLocal
                TransactionContext transactionContext = TransactionThreadLocal.CONTEXT_THREADLOCAL.get();

                //If the current transaction context object is not null, do the following
                if (Objects.nonNull(transactionContext)) {

                    //The transaction context object is passed to the remote method as an RPC interface parameter
                    SimpleRpcContext.getContext().setAttachment(TransactionConstant.TRANSACTION_CONTEXT, JSON.toJSONString(transactionContext));
                    log.info("2. Pass the transaction participant context object as an RPC interface parameter to the remote method:" + JSON.toJSONString(transactionContext));

                    //Add a transaction participant for the current transaction, and the participant is the called remote method
                    Participant participant = new Participant();
                    participant.setTransactionId(transactionContext.getTransactionId());
                    participant.setMessageModel(myth.deliveryModel().getCode());
                    participant.setDestination(myth.destination());
                    Class targetClass = Class.forName(myth.servicePath());
                    participant.setTargetClass(targetClass);
                    participant.setMethodName(method.getName());
                    participant.setParameterTypes(method.getParameterTypes());
                    participant.setArguments(args);

                    TransactionCoordinatorSupport transactionCoordinatorSupport = ApplicationContextHolder.getBean(TransactionCoordinatorSupport.class);
                    transactionCoordinatorSupport.addParticipant(participant);
                    log.info("3. Add transaction participant:" + participant.getTargetClass() + "." + participant.getMethodName());
                }

                return this.delegate.invoke(proxy, method, args);
            } catch (Throwable t) {
                //throwable.printStackTrace();
                log.error(t.getMessage());
                //Record the error message
                RPCErrorInfo rpcErrorInfo = new RPCErrorInfo();
                rpcErrorInfo.setCode(1);
                rpcErrorInfo.setErrorMsg(t.getMessage());
                TransactionThreadLocal.RPC_ERROR_INFO_THREADLOCAL.set(rpcErrorInfo);
                return handleRtnValue(method.getReturnType());
            }
        }
    }

    public Object handleRtnValue(final Class clazz) throws Exception {
        if (boolean.class.equals(clazz) || Boolean.class.equals(clazz)) {
            return false;
        } else if (byte.class.equals(clazz) || Byte.class.equals(clazz)) {
            return 0;
        } else if (short.class.equals(clazz) || Short.class.equals(clazz)) {
            return 0;
        } else if (int.class.equals(clazz) || Integer.class.equals(clazz)) {
            return 0;
        } else if (long.class.equals(clazz) || Long.class.equals(clazz)) {
            return 0L;
        } else if (float.class.equals(clazz) || Float.class.equals(clazz)) {
            return 0.0f;
        } else if (double.class.equals(clazz) || Double.class.equals(clazz)) {
            return 0.0d;
        } else if (String.class.equals(clazz)) {
            return "";
        } else if (Void.TYPE.equals(clazz)) {
            return "";
        }
        final Constructor[] constructors = clazz.getDeclaredConstructors();
        Constructor constructor = constructors[constructors.length - 1];
        constructor.setAccessible(true);
        final Class[] paramClasses = constructor.getParameterTypes();
        Object[] args = new Object[paramClasses.length];
        for (int i = 0; i < paramClasses.length; i++) {
            Class clazzes = paramClasses[i];
            if (clazzes.isPrimitive()) {
                args[i] = 0;
            } else {
                args[i] = null;
            }
        }
        return constructor.newInstance(args);
    }


    public void setDelegate(InvocationHandler delegate) {
        this.delegate = delegate;
    }
}
